package com.netcross.myapplication.ui.home;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.bin.david.form.listener.OnColumnItemClickListener;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.netcross.myapplication.BaseActivity;
import com.netcross.myapplication.R;
import com.netcross.myapplication.UpdateActivity;
import com.netcross.myapplication.bean.TrainMain;
import com.netcross.myapplication.databinding.FragmentHomeBinding;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private SmartTable<TrainMain> table;
        private long mBackPressed;


    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //标记请求
            if (msg.what == 0 || msg.what == 1 || msg.what ==2) {
                List<TrainMain> list = (List<TrainMain>) msg.obj;
                final Column<String> demand_order_number = new Column<>("需求单号", "demand_order_number");
                final Column<String> waybill_id = new Column<>("运单ID", "waybill_id");
                final Column<String> type_of_transport = new Column<>("运输类型", "type_of_transport");
                final Column<String> mode_of_transport = new Column<>("运输方式", "mode_of_transport");
                final Column<String> dangerous_goods_labe = new Column<>("危险品标志", "dangerous_goods_labe");
                final Column<String> transportation_plan_numbe = new Column<>("运输计划号", "transportation_plan_numbe");
                final Column<String> sending_station_telegram_code = new Column<>("发送站电报码", "sending_station_telegram_code");
                final Column<String> sending_station_tmis = new Column<>("发送站tmis", "sending_station_tmis");
                final Column<String> sending_station_name = new Column<>("发送站名称", "sending_station_name");
                final Column<String> updateing = new Column<>("修改按钮", "updateing");

                TableData<TrainMain> tableData = new TableData("车辆主表", list, updateing, demand_order_number, waybill_id, type_of_transport, mode_of_transport,
                        dangerous_goods_labe, transportation_plan_numbe, sending_station_telegram_code, sending_station_tmis, sending_station_name);
                table = getActivity().findViewById(R.id.table);
                updateing.setFixed(true);
                updateing.setOnColumnItemClickListener(new OnColumnItemClickListener<String>() {
                    @Override
                    public void onClick(Column<String> column, String s, String s2, int i) {
                        goToUpdateActivity(demand_order_number.getDatas().get(i));
                        Toast.makeText(getActivity(), "点击了" + demand_order_number.getDatas().get(i), Toast.LENGTH_SHORT).show();
                    }
                });

                table.setTableData(tableData);
                table.getConfig().setContentStyle(new FontStyle(50, Color.BLACK));
            }
            if (msg.what == 1){
//                FrameLayout frameLayout = getActivity().findViewById(R.id.homeframeLayout);
//                frameLayout.getLayoutParams().height =
                FloatingActionButton button = (FloatingActionButton) getActivity().findViewById(R.id.fab);
                Drawable img = getResources().getDrawable(R.drawable.back);
                button.setImageDrawable(img);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                          Toast.makeText(getActivity(), "返回", Toast.LENGTH_SHORT).show();
                          new Thread(new Runnable() {

            @Override
            public void run() {
                List<TrainMain> list = getTableData();
                Message message = new Message();
                message.what = 2;
                message.obj = list;
                handler.sendMessage(message);
            }
        }).start();
                    }
                });

            }

            if (msg.what == 2){
                FloatingActionButton button = (FloatingActionButton) getActivity().findViewById(R.id.fab);
                Drawable img = getResources().getDrawable(R.drawable.search);
                button.setImageDrawable(img);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        View view1 = getLayoutInflater().inflate(R.layout.dialog, null);
                EditText editText = (EditText) view1.findViewById(R.id.seachDialogEditText);
                Spinner spinner = (Spinner) view1.findViewById(R.id.seachDialogSpinner);
                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("搜索")//设置对话框的标题
                        .setView(view1)
                        //设置对话框的按钮
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getActivity(), "点击了取消按钮", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("查询", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //TODO 增加输入数据的处理
                                String queryConditions = editText.getText().toString(); //模糊查询条件
                                String queryField = spinner.getSelectedItem().toString();//要查询的数据项
                                Toast.makeText(getActivity(), "点击了查询的按钮" + queryConditions + queryField, Toast.LENGTH_SHORT).show();
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        List<TrainMain> list = getTableDataLike(queryConditions,queryField);
                                        Message message = new Message();
                                        message.what = 1;
                                        message.obj = list;
                                        handler.sendMessage(message);
                                    }
                                }).start();

                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();

                    }
                });


            }
        }
    };


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        initPython();
        new Thread(new Runnable() {

            @Override
            public void run() {
                List<TrainMain> list = getTableData();
                Message message = new Message();
                message.what = 0;
                message.obj = list;
                handler.sendMessage(message);
            }
        }).start();

        return root;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        FloatingActionButton floatingActionButton = (FloatingActionButton) getActivity().findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View view1 = getLayoutInflater().inflate(R.layout.dialog, null);
                EditText editText = (EditText) view1.findViewById(R.id.seachDialogEditText);
                Spinner spinner = (Spinner) view1.findViewById(R.id.seachDialogSpinner);
                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("搜索")//设置对话框的标题
                        .setView(view1)
                        //设置对话框的按钮
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getActivity(), "点击了取消按钮", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("查询", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //TODO 增加输入数据的处理
                                String queryConditions = editText.getText().toString(); //模糊查询条件
                                String queryField = spinner.getSelectedItem().toString();//要查询的数据项
                                Toast.makeText(getActivity(), "点击了查询的按钮" + queryConditions + queryField, Toast.LENGTH_SHORT).show();
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        List<TrainMain> list = getTableDataLike(queryConditions,queryField);
                                        Message message = new Message();
                                        message.what = 1;
                                        message.obj = list;
                                        handler.sendMessage(message);
                                    }
                                }).start();

                                dialog.dismiss();
                            }
                        }).create();
                dialog.show();

            }
        });


    }







    //将获取的json数据转储成TrainMain list 待使用
    private List<TrainMain> getTableData() {
        List<TrainMain> list = new ArrayList<>();
        List<PyObject> jsonList = callPythonCode();
        Gson gson = new Gson();
        for (int i = 0; i < jsonList.size(); i++) {
            String strTypeJson = String.valueOf(jsonList.get(i));
            TrainMain trainMain = gson.fromJson(strTypeJson, TrainMain.class);
//                JSONObject jsonObject = JSONUtil.parseObj(strTypeJson);
            list.add(new TrainMain(
                    trainMain.getDemand_order_number(),
                    trainMain.getWaybill_id(),
                    trainMain.getType_of_transport(),
                    trainMain.getMode_of_transport(),
                    trainMain.getDangerous_goods_labe(),
                    trainMain.getTransportation_plan_numbe(),
                    trainMain.getSending_station_telegram_code(),
                    trainMain.getSending_station_tmis(),
                    trainMain.getSending_station_name(),
                    "修改"));
        }
        return list;
    }

    //同上
    private List<TrainMain> getTableDataLike(String queryConditions,String queryField) {
        List<TrainMain> list = new ArrayList<>();
        List<PyObject> jsonList = selectTableMainByLike(queryConditions,queryField);
        Gson gson = new Gson();
        for (int i = 0; i < jsonList.size(); i++) {
            String strTypeJson = String.valueOf(jsonList.get(i));
            TrainMain trainMain = gson.fromJson(strTypeJson, TrainMain.class);
//                JSONObject jsonObject = JSONUtil.parseObj(strTypeJson);
            list.add(new TrainMain(
                    trainMain.getDemand_order_number(),
                    trainMain.getWaybill_id(),
                    trainMain.getType_of_transport(),
                    trainMain.getMode_of_transport(),
                    trainMain.getDangerous_goods_labe(),
                    trainMain.getTransportation_plan_numbe(),
                    trainMain.getSending_station_telegram_code(),
                    trainMain.getSending_station_tmis(),
                    trainMain.getSending_station_name(),
                    "修改"));
        }
        return list;
    }

    // 初始化Python环境
    void initPython() {
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(getActivity()));
        }
    }

    //获取表的内容
    List<PyObject> callPythonCode() {
        Python py = Python.getInstance();
        PyObject obj = py.getModule("wbc").get("relodeTable").call();
        List<PyObject> jsonList = obj.asList();
        return jsonList;
    }
    //按搜索框中获取的内容模糊搜索

     List<PyObject> selectTableMainByLike(String queryConditions,String queryField){
        Python py = Python.getInstance();
       PyObject obj = null;
        if (queryField.equals("需求单号")){
             obj = py.getModule("wbc").get("vagueSelectByDemandOrderNumber").call(queryConditions);

        }else if (queryField.equals("运单ID")){
             obj= py.getModule("wbc").get("vagueSelectByWaybillId").call(queryConditions);

        }
         List<PyObject> jsonList = obj.asList();
        return jsonList;
    }



    private void goToUpdateActivity(String vaule) {
        Intent intent = new Intent(getActivity(), UpdateActivity.class);
        intent.putExtra("demand_order_number", vaule);
        this.startActivity(intent);
        getActivity().finish();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}